package ynu.lcy.elememicroserviceuserauthservice9091.controller;



import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import ynu.lcy.dto.User.LoginDTO;
import ynu.lcy.dto.User.RegisterDTO;
import ynu.lcy.elememicroservicecommon.annotation.AuthCheck;
import ynu.lcy.elememicroservicecommon.constant.UserConstant;
import ynu.lcy.elememicroservicecommon.exception.BusinessException;
import ynu.lcy.elememicroservicecommon.utils.BaseResponse;
import ynu.lcy.elememicroservicecommon.utils.ErrorCode;
import ynu.lcy.elememicroservicecommon.utils.ResultUtils;

import ynu.lcy.elememicroservicecommon.utils.TokenUtils;
import ynu.lcy.elememicroserviceuserauthservice9091.chain.AuthenticationContext;

import ynu.lcy.elememicroserviceuserauthservice9091.entity.User;
import ynu.lcy.elememicroserviceuserauthservice9091.service.AuthenticationService;
import ynu.lcy.elememicroserviceuserauthservice9091.service.UserService;
import ynu.lcy.vo.TokenVo;
import ynu.lcy.vo.UserVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;

import static ynu.lcy.elememicroservicecommon.constant.CommonConstant.ACCESS_TOKEN;
import static ynu.lcy.elememicroservicecommon.constant.CommonConstant.REFRESH_TOKEN;


@Api(tags = "权限认证接口")
@RestController
@CrossOrigin
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private AuthenticationService service;


    @ApiOperation("用户登录")
    @PostMapping("/login")
    @Transactional
    public BaseResponse<TokenVo> login(@ApiParam("登录信息") @RequestBody LoginDTO loginDTO){
        //加密
        String pwd = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        //构建上下文对象
        AuthenticationContext authenticationContext = new AuthenticationContext(loginDTO.getUserPhone(), pwd);
        //认证流程
        User user = service.authenticate(authenticationContext);
        //生成AccessToken
        String token = service.createToken(user,ACCESS_TOKEN);
        //生成refreshToken
        String refreshToken = service.createToken(user,REFRESH_TOKEN);
        //最后进行缓存
        service.saveTokenToRedis(user,token,refreshToken);
        return  ResultUtils.success(new TokenVo(token,refreshToken));
    }

    @ApiOperation("通过refreshToken换新令牌")
    @GetMapping("/refresh")
    public BaseResponse<TokenVo> refresh(HttpServletRequest httpServletRequest){
        return  ResultUtils.success(service.updateAccessToken(httpServletRequest));
    }


}
